# 日志类
import logging
from datetime import datetime
import os
import glob

from zz import zz_code

# 创建日志记录器
logger = None


# logging.INFO = 20
# logging.DEBUG = 10
def of():
    delete_old_logs(7)  # 删除旧日志
    global logger
    if logger is not None:
        return logger
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    # DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40
    log_level = int(zz_code.env("LOG_LEVEL", '20'))

    # 创建格式化器
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s [%(lineno)d] - %(message)s')

    # 创建并添加控制台处理器
    if zz_code.is_dev():
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        console_handler.setLevel(logging.INFO)
        logger.addHandler(console_handler)

    # 创建并添加文件处理器
    folder_path = './logs'
    if not os.path.exists(folder_path):
        # 如果文件夹不存在，则创建文件夹
        os.makedirs(folder_path)

    now = datetime.now()
    now_format = now.strftime("%Y-%m-%d")
    logfile_name = "{}.log".format(now_format)
    file_handler = logging.FileHandler("{}/{}".format(folder_path, logfile_name), mode='a', encoding='UTF-8')
    file_handler.setFormatter(formatter)
    file_handler.setLevel(log_level)
    logger.addHandler(file_handler)
    return logger


def delete_old_logs(threshold_days):
    """
    删除旧日志
    :param threshold_days: 删除n天前文件（修改时间）
    """
    files = glob.glob("./logs/*.log")
    delete_date = zz_code.date_sub_day(zz_code.date_today(), threshold_days)
    for file in files:
        if os.path.isfile(file):
            file_create_date = zz_code.date_from_timestamp(os.path.getmtime(file))
            if file_create_date < delete_date:
                os.remove(file)
            # if os.path.getmtime(file) < time.time() - threshold_days * 24 * 3600:
            #     os.remove(file)
